<template>
  <div class="profile-editor bg-white/90 backdrop-blur-2xl rounded-2xl shadow-xl overflow-hidden p-6">
    <form @submit.prevent="saveProfile" class="space-y-6">

      <!-- 照片编辑区 -->
      <div class="grid grid-cols-2 gap-4">
        <!-- 头像上传 -->
        <div class="space-y-2">
          <label class="form-label">头像</label>
          <div class="relative w-24 h-24 group">
            <img :src="avatarPreview || formData.avatar" alt="Avatar" class="w-full h-full rounded-full object-cover border-2 border-gray-200">
            <div @click="triggerFileInput('avatar')" class="absolute inset-0 bg-black/50 rounded-full flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2-2V9z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
            </div>
          </div>
          <input type="file" ref="avatarInput" @change="handleFileChange('avatar', $event)" class="hidden" accept="image/*">
        </div>

        <!-- 背景上传 -->
        <div class="space-y-2">
          <label class="form-label">背景</label>
          <div class="relative w-full h-24 rounded-lg group overflow-hidden">
            <img :src="bgPreview || formData.backgroundImage" alt="Background" class="w-full h-full object-cover border-2 border-gray-200 rounded-lg">
            <div @click="triggerFileInput('bg')" class="absolute inset-0 bg-black/50 flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
            </div>
          </div>
          <input type="file" ref="bgInput" @change="handleFileChange('bg', $event)" class="hidden" accept="image/*">
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="form-section">
        <div class="grid grid-cols-2 gap-x-4 gap-y-5">
          <div class="form-group">
            <label for="nickname" class="form-label">昵称</label>
            <input type="text" id="nickname" v-model="formData.nickname" class="form-input" required>
          </div>
          <div class="form-group">
            <label for="birthday" class="form-label">生日</label>
            <input type="date" id="birthday" v-model="formData.birthday" class="form-input" required>
          </div>
          <div class="form-group">
            <label class="form-label">性别</label>
            <div class="flex items-center space-x-4 pt-2">
              <label class="inline-flex items-center cursor-pointer"><input type="radio" v-model="formData.gender" value="male" class="form-radio"><span class="ml-2">男</span></label>
              <label class="inline-flex items-center cursor-pointer"><input type="radio" v-model="formData.gender" value="female" class="form-radio"><span class="ml-2">女</span></label>
            </div>
          </div>
          <div class="form-group">
            <label for="hometown" class="form-label">家乡</label>
            <input type="text" id="hometown" v-model="formData.hometown" class="form-input">
          </div>
        </div>
      </div>
      
      <!-- 学校信息 -->
      <div class="form-section">
        <div class="grid grid-cols-2 gap-x-4 gap-y-5">
          <div class="form-group">
            <label for="schoolName" class="form-label">学校名称</label>
            <input type="text" id="schoolName" v-model="formData.schoolName" class="form-input">
          </div>
          <div class="form-group">
            <label for="enrollmentDate" class="form-label">入学时间</label>
            <input type="month" id="enrollmentDate" v-model="formData.enrollmentDate" class="form-input" required>
          </div>
          <div class="form-group">
            <label for="major" class="form-label">专业</label>
            <input type="text" id="major" v-model="formData.major" class="form-input">
          </div>
          <div class="form-group">
            <label for="class" class="form-label">班级</label>
            <input type="text" id="class" v-model="formData.class" class="form-input" placeholder="例如: 软件2101班">
          </div>
        </div>
      </div>

      <!-- 简介 -->
      <div class="form-section">
        <label for="bio" class="form-label">个人简介</label>
        <textarea id="bio" v-model="formData.bio" class="form-textarea" placeholder="介绍一下自己，让大家更好地认识你..." rows="3" maxlength="100"></textarea>
        <p class="text-xs text-right text-gray-500 mt-1">{{ formData.bio.length }}/100</p>
      </div>
      
      <!-- 标签编辑 -->
      <div class="form-section">
        <label class="form-label">我的标签</label>
        <div class="flex flex-wrap gap-2 mb-3">
          <span v-for="(tag, index) in formData.tags" :key="index" class="tag-item">
            {{ tag }}
            <button type="button" @click="removeTag(index)" class="tag-remove-btn">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" /></svg>
            </button>
          </span>
        </div>
        <div class="flex" v-if="formData.tags.length < 6">
          <select v-model="selectedTag" class="form-input flex-grow">
            <option value="" disabled>从推荐标签中选择...</option>
            <optgroup v-for="(tags, category) in availableCategorizedTags" :key="category" :label="category">
              <option v-for="tag in tags" :key="tag" :value="tag">{{ tag }}</option>
            </optgroup>
          </select>
          <button type="button" @click="addSelectedTag" class="ml-2 shrink-0 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors" :disabled="!selectedTag">添加</button>
        </div>
        <p class="text-xs text-gray-500 mt-1">最多可选择 6 个标签</p>
      </div>

      <!-- 按钮组 -->
      <div class="flex justify-end space-x-3 pt-4">
        <button type="button" @click="cancelEdit" class="cancel-btn">取消</button>
        <button type="submit" class="save-btn">保存修改</button>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: 'UserProfileEditor',
  props: {
    user: {
      type: Object,
      required: true
    }
  },
  data() {
    // 从用户年龄计算大致的生日（如果没有提供）
    const calculateBirthday = () => {
      if (this.user.birthday) return this.user.birthday;

      const today = new Date();
      const birthYear = today.getFullYear() - (this.user.age || 20);
      return `${birthYear}-01-01`; // 默认1月1日
    };

    // 获取当前年月作为默认入学时间
    const getDefaultEnrollmentDate = () => {
      if (this.user.enrollmentDate) return this.user.enrollmentDate;
      const d = new Date();
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      return `${year}-${month}`;
    };

    return {
      avatarPreview: null,
      bgPreview: null,
      selectedTag: '',
      categorizedTags: {
        '技术&开发': ['Vue', 'React', 'Angular', 'JavaScript', 'TypeScript', '前端开发', '后端开发', '全栈开发', 'UI设计', 'UX设计'],
        '生活&爱好': ['摄影', '旅行', '美食', '电影', '音乐', '阅读', '健身'],
        '兴趣&娱乐': ['游戏', '动漫', '宠物', '猫咪爱好者', '狗狗爱好者']
      },
      formData: {
        nickname: this.user.nickname || '',
        gender: this.user.gender || 'male',
        birthday: calculateBirthday(),
        enrollmentDate: getDefaultEnrollmentDate(),
        schoolName: this.user.schoolName || '',
        major: this.user.major || '',
        class: this.user.class || '',
        hometown: this.user.hometown || '',
        bio: this.user.bio || '',
        avatar: this.user.avatar || 'https://via.placeholder.com/150',
        backgroundImage: this.user.backgroundImage || 'https://ts4.tc.mm.bing.net/th/id/OIP-C.Hbkk9AkInuzpK6UyPKXyYQHaEK?rs=1&pid=ImgDetMain&o=7&rm=3',
        tags: [...(this.user.tags || [])]
      }
    };
  },
  computed: {
    // 获取可用的、分类的标签列表（排除已选的）
    availableCategorizedTags() {
      const available = {};
      for (const category in this.categorizedTags) {
        const tags = this.categorizedTags[category].filter(tag => !this.formData.tags.includes(tag));
        if (tags.length > 0) {
          available[category] = tags;
        }
      }
      return available;
    }
  },
  methods: {
    // 触发文件输入框
    triggerFileInput(type) {
      if (type === 'avatar') {
        this.$refs.avatarInput.click();
      } else if (type === 'bg') {
        this.$refs.bgInput.click();
      }
    },

    // 处理文件选择
    handleFileChange(type, event) {
      const file = event.target.files[0];
      if (!file) return;

      // 简单验证文件类型和大小
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件！');
        return;
      }
      if (file.size > 2 * 1024 * 1024) { // 2MB
        alert('文件大小不能超过 2MB！');
        return;
      }

      // 创建预览URL
      const reader = new FileReader();
      reader.onload = (e) => {
        if (type === 'avatar') {
          this.avatarPreview = e.target.result;
          this.formData.avatar = e.target.result; // 在实际应用中，这里应该是上传后的URL
        } else if (type === 'bg') {
          this.bgPreview = e.target.result;
          this.formData.backgroundImage = e.target.result; // 同上
        }
      };
      reader.readAsDataURL(file);
    },

    // 移除标签
    removeTag(index) {
      this.formData.tags.splice(index, 1);
    },

    // 添加从下拉框选择的标签
    addSelectedTag() {
      if (this.selectedTag && !this.formData.tags.includes(this.selectedTag) && this.formData.tags.length < 6) {
        this.formData.tags.push(this.selectedTag);
        this.selectedTag = '';
      }
    },
    saveProfile() {
      // 计算年龄（基于生日）
      const birthDate = new Date(this.formData.birthday);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();

      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }

      // 创建更新后的用户对象
      const updatedUser = {
        ...this.user,
        nickname: this.formData.nickname,
        gender: this.formData.gender,
        birthday: this.formData.birthday,
        age: age,
        enrollmentDate: this.formData.enrollmentDate,
        schoolName: this.formData.schoolName,
        major: this.formData.major,
        class: this.formData.class,
        hometown: this.formData.hometown,
        bio: this.formData.bio,
        avatar: this.formData.avatar,
        backgroundImage: this.formData.backgroundImage,
        tags: [...this.formData.tags]
      };

      // 触发保存事件
      this.$emit('save', updatedUser);
    },
    cancelEdit() {
      // 触发取消事件
      this.$emit('cancel');
    }
  }
};
</script>

<style scoped>
.profile-editor {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
  height: 100%;
  overflow-y: auto;
}

/* 美化滚动条 (适用于 Webkit 浏览器) */
.profile-editor::-webkit-scrollbar {
  width: 6px;
}
.profile-editor::-webkit-scrollbar-track {
  background: transparent;
}
.profile-editor::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.25);
  border-radius: 3px;
  border: 1px solid transparent;
}
.profile-editor::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.4);
}


.form-section {
  @apply bg-white/60 p-4 rounded-xl border border-gray-200/80;
}

.form-label {
  @apply block text-sm font-semibold text-gray-600 mb-1.5;
}

.form-input, .form-textarea, .form-select {
  @apply w-full px-3 py-2 border border-gray-300 rounded-lg bg-white/80 text-gray-800 text-sm;
  @apply focus:outline-none focus:ring-2 focus:ring-green-400 focus:border-transparent transition;
}

.form-textarea {
  @apply resize-y min-h-[70px];
}

.form-radio {
  @apply appearance-none w-4 h-4 border-2 border-gray-300 rounded-full bg-white transition;
  @apply checked:bg-green-500 checked:border-green-500 checked:ring-2 checked:ring-offset-1 checked:ring-green-500;
}

.tag-item {
  @apply bg-green-100 text-green-800 text-xs font-semibold px-2.5 py-1 rounded-full flex items-center gap-1.5;
}
.tag-remove-btn {
  @apply text-green-600 hover:text-white hover:bg-green-500 rounded-full transition-colors;
}

.save-btn, .cancel-btn {
  @apply px-5 py-2 rounded-lg font-semibold text-sm transition-all duration-200;
}

.save-btn {
  @apply bg-green-500 text-white hover:bg-green-600 hover:shadow-lg hover:shadow-green-500/30;
}
.cancel-btn {
  @apply bg-gray-200 text-gray-700 hover:bg-gray-300;
}
</style>
